package com.zmn.plat.admin.controller.product.categorybrand;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.google.common.collect.Lists;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dictionary.GlobalDict;
import com.zmn.common.exception.ZmnException;
import com.zmn.common.utils.logger.LoggerUtil;
import com.zmn.common.utils.office.ExcelUtil;
import com.zmn.plat.manager.interfaces.cache.BrandCache;
import com.zmn.plat.model.entity.brand.BaseBrand;
import com.zmn.plat.model.entity.brand.BaseBrandQuery;
import com.zmn.plat.model.entity.category.BaseCategory;
import com.zmn.plat.model.entity.product.categorybrand.CategoryBrandQuery;
import com.zmn.plat.model.vo.product.categorybrand.CategoryBrandVo;
import com.zmn.plat.services.interfaces.brand.BaseBrandService;
import com.zmn.plat.services.interfaces.category.BaseCategoryService;
import com.zmn.plat.services.interfaces.product.categorybrand.CategoryBrandService;

/**
 * 产品分类开通品牌表基础查询Controller
 *
 * @author tanghongjun
 * @since 2020-08-19 11:18:36
 */
@RestController
@RequestMapping("/product/categorybrand/")
public class CategoryBrandListController extends CategoryBrandBaseController {

    private Logger logger = LoggerFactory.getLogger(CategoryBrandListController.class);

    @Resource
    private CategoryBrandService categoryBrandService;
    @Resource
    private BrandCache brandCache;
    @Resource
    private BaseBrandService baseBrandService;
    @Resource
    private BaseCategoryService baseCategoryService;

    /**
     * 列表
     */
    @RequestMapping("list")
    @RequiresPermissions("/product/categorybrand/list.action")
    public ModelAndView list(@ModelAttribute CategoryBrandQuery query) {
        List<CategoryBrandVo> items = categoryBrandService.listPageByQuery(query);
        BaseCategory baseCategory = baseCategoryService.findByKey(query.getCategId());
        ModelAndView mav = new ModelAndView("product/categorybrand/list");
        List<BaseBrand> brandList = brandCache.listAll();
        mav.addObject("items", items);
        mav.addObject("vo", query);
        mav.addObject("brandList", brandList);
        mav.addObject("statuses", GlobalDict.getStatusList(false));
        mav.addObject("categName",baseCategory.getName());

        return mav;
    }

    /**
     * 新增品牌信息
     */
    @RequestMapping("addEditView")
    @RequiresPermissions("/product/categorybrand/addEditView.action")
    public ModelAndView info(@ModelAttribute BaseBrandQuery query) {
        List<BaseBrand> items = baseBrandService.listUnlinkedBrandPageByQuery(query);
        BaseCategory baseCategory = baseCategoryService.findByKey(query.getCategTwoId());
        ModelAndView mav = new ModelAndView("product/categorybrand/brand/list");
        mav.addObject("items", items);
        mav.addObject("vo", query);
        mav.addObject("categName",baseCategory.getName());
        return mav;
    }

    /**
     * 描述: 关联品牌导出excel
     *
     * @param query
     *            查询条件
     * @author tanbiao
     **/
    @RequestMapping(value = "outputExcel")
    public void outputExcel(HttpServletResponse response, CategoryBrandQuery query) {
        Integer pageSize = getExportPageLimit(response);
        query.setPageSize(pageSize);

        // 头，品牌id/排序/品牌名称/品牌类型/状态/前台二级分类
        BaseCategory baseCategory = baseCategoryService.findByKey(query.getCategId());
        if (Objects.isNull(baseCategory)) {
            response.setContentType("text/html;charset=utf-8");
            response.setStatus(EXPORT_LIMIT_ERROR_CODE);
            try {
                response.getWriter().print(EXPORT_LIMIT_ERROR_CODE);
            } catch (IOException e) {

            }
            throw new ZmnException("二级分类不存在，导出失败");
        }

        List<CategoryBrandVo> items = categoryBrandService.listPageByQuery(query);
        ArrayList<List> arrayList = Lists.newArrayListWithExpectedSize(items.size() + 1);
        List<String> column = Arrays.asList("品牌ID", "排序", "品牌名称", "品牌类型", "状态", "前台二级分类");
        arrayList.add(column);
        if (!CollectionUtils.isEmpty(items)) {
            items.forEach(vo -> {
                List<String> item = new ArrayList<>();
                item.add(String.valueOf(vo.getBrandId()));
                item.add(String.valueOf(vo.getSort()));
                item.add(vo.getBrandName());
                item.add(Objects.equals(vo.getType(), GlobalConsts.NO) ? "国产品牌" : "国外品牌");
                item.add(Objects.equals(GlobalConsts.YES, vo.getStatus()) ? "启用" : "禁用");
                item.add(baseCategory.getName());
                arrayList.add(item);
            });
        }

        try {
            String name = "品牌关联.xlsx";
            name = new String(name.getBytes(), "ISO8859-1");
            ExcelUtil.export(response, arrayList, name, "sheet");
        } catch (Exception e) {
            LoggerUtil.error(this.getClass(), "导出品牌关联" + e.getMessage(), e);
        }
    }

}
